package com.webrtc.demo

import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.webrtc.demo.call.RTCSignalClient
import com.webrtc.demo.util.logD
import kotlinx.android.synthetic.main.activity_test.*


class TestActivity : AppCompatActivity() {

    companion object {
        const val TAG = "TestActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)


        btn_enter.setOnClickListener {
            val fromId = et_from_id.text.toString()
            val toId = et_to_id.text.toString()
//            MainActivity.launch(this, fromId, toId)
            ChatActivity.launch(this, fromId, toId)
        }

        val peer1 = "SM-N9500"
        val peer2 = "LIO-AN00"

        ConnectionManager.init(application)

        if (Build.MODEL == peer1) {
            RTCSignalClient.init(peer1, "http://18.162.220.173:3131")

            // 作为发送方
            val connection = ConnectionManager.get(peer2)

            // 文本监听
            val listener: (String) -> Unit = {
                logD(TAG, it)

                runOnUiThread { showText(it) }

                connection.textStation.send("我是三星")
            }
            connection.textStation.registerListener(listener)

            button2.setOnClickListener { connection.connect() }

            // app退出时关闭，聊天页面只需要移除监听，不用断开通道
            button3.setOnClickListener {
                connection.close()

                // connection.textStation.unregisterListener(listener)
            }

        } else if (Build.MODEL == peer2) {
            RTCSignalClient.init(peer2, "http://18.162.220.173:3131")

            // 接收方
            val connection = ConnectionManager.get(peer1)

            connection.textStation.registerListener {
                logD(TAG, it)

                runOnUiThread { showText(it) }

                // connection.textStation.send("我是华为")
            }
        }

    }

    private fun showText(msg: String) {
        textView.text = "${textView.text}\n$msg "
    }
}
